import React, { useEffect, useState } from 'react'
import { Button, Form, message, Modal, notification, Space, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import {
  getProductClassConfigByType,
  getProductFabricPageList,
  productFabricConfigimportExcel,
  productFabricConfigUpdateStatus,
} from '@/api/goods'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import { ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { useNavigate } from 'react-router-dom'
import { IMPORT_FILE_ENUM, STATUSBANDOPTIONS } from '@/constant'
import { ImportOutlined, PlusOutlined } from '@ant-design/icons'
import { downloadByUrl, importNotification } from '@/utils/util'
import ImportFileModal from '@/components/ImportFileModal'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [form] = useForm()
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  // upload
  const [FormUpload] = useForm()
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const ProDevSeason = useGetProDevSeason('seasonName')
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(getProductFabricPageList, {
    form: form,
    defaultFieldsParams: {
      status: 1,
    },
    immediatelySend: false,
  })
  useEffect(() => {
    getProductClassConfig()
    search({ ...params, status: 1 })
  }, [])
  const selectRows = (keys: React.Key[]) => {
    setselectedRowKeys(keys)
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    const res = await productFabricConfigimportExcel<{ linkUrl: string }>(file).finally(() => {
      setexportLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search(params)
      onUploadFileCancel()
    }
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  return (
    <PageContainer className="goods_fabric_page">
      <SearchForm
        params={params}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['searchName'], form)}
        form={form}
        searchConfig={[
          { label: '面料', name: 'searchName', type: 'Input', placeholder: '面料编码/面料名称' },
          { label: '开发季', name: 'devSeason', type: 'Select', option: ProDevSeason },
          { label: '大类', name: 'bigClassId', type: 'Select', option: classBig },
          {
            label: '是否集约',
            name: 'intensiveStatus',
            type: 'Select',
            option: [
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ],
          },
          { label: '状态', name: 'status', type: 'Select', option: STATUSBANDOPTIONS },
        ]}
        onFinish={(vals: any) => {
          setselectedRowKeys([])
          search(vals)
        }}
        onReset={() => {
          setselectedRowKeys([])
          reset()
        }}
        extra={
          <div className="table_extra_flex">
            <PermissionButton
              permission="batchAddFabric"
              type="primary"
              onClick={() => {
                setisUploadFileShow(true)
              }}
              icon={<ImportOutlined />}
            >
              批量新建面料
            </PermissionButton>
            <PermissionButton
              permission="onFabric"
              onClick={async () => {
                if (selectedRowKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                const res = await productFabricConfigUpdateStatus({ ids: selectedRowKeys, status: 1 })
                if (res.code === 200) {
                  message.success('操作成功')
                  setselectedRowKeys([])
                  search(params)
                }
              }}
            >
              启用面料
            </PermissionButton>
            <PermissionButton
              permission="offFabric"
              onClick={async () => {
                if (selectedRowKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                const res = await productFabricConfigUpdateStatus({ ids: selectedRowKeys, status: 0 })
                if (res.code === 200) {
                  message.success('操作成功')
                  setselectedRowKeys([])
                  search(params)
                }
              }}
            >
              停用面料
            </PermissionButton>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        columns={useIndexColumns({ navigate })}
        {...tableProps}
        rowKey={(rows) => rows.fabricId}
        isScrollY
      />
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.GOODS_FABRIC_IMPORT}
      ></ImportFileModal>
    </PageContainer>
  )
}

export default Index
